﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;
using System.Net.Mail;
using System.Xml.Serialization;
using System.IO;
using System.ServiceModel;


namespace EnviarCorreo
{
    public class Program
    {
        private static MessageQueue msgQ = null;
        private static object lockObject = new object();

        static void Main(string[] args)
        {
            string queuePath = @".\private$\WebsiteEmails";
            ColaExiste(queuePath);
            msgQ = new MessageQueue(queuePath);
            msgQ.Formatter = new BinaryMessageFormatter();
            msgQ.MessageReadPropertyFilter.SetAll();
            msgQ.ReceiveCompleted += new ReceiveCompletedEventHandler(msgQ_ReceiveCompleted);
            msgQ.BeginReceive();
            while (Console.ReadKey().Key != ConsoleKey.Q)
            {
                // Press q to exit
            }
        }

        static void msgQ_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
        {
            lock (lockObject)
            {
                // The message is plain text.
                EmailMessage msg = (EmailMessage)e.Message.Body;
                String xx = SendMessage(msg, "slideshowdsd@gmail.com", "slideshow2012", true);
                Console.WriteLine("Message received: " + msg.Message);
            }
            // Listen for the next message
            msgQ.BeginReceive();
        }


        public static void ColaExiste(string queuePath)
        {
            //if this queue doesn't exist we will create it
            if (!MessageQueue.Exists(queuePath))
                MessageQueue.Create(queuePath);
        }

        public static string SendMessage(EmailMessage message, string username, string password, bool enableSsl)
        {

            string serializedMessage = SerializeMessage(message);
            string correos = message.To;
            var mails = correos.Split(';');

            SmtpClient sc = new SmtpClient();
            //sc.Timeout = 250;//Tiempo de conexión
            sc.Host = "smtp.gmail.com";
            sc.EnableSsl = true;
            sc.Credentials =
            new System.Net.NetworkCredential
            {
                UserName = username,//Nombre de usuario de correo
                Password = password//password
            };


            using (MailMessage mm = new MailMessage())
            {
                mm.From = new System.Net.Mail.MailAddress(message.From, message.From, System.Text.Encoding.UTF8);
                mm.Subject = message.Subject;

                //Cargamos el contenido del mail.
                mm.Body = message.Message;
                mm.Priority = MailPriority.Normal;

                //Cargamos todos los mails que se ingresaron
                //en el campor de text
                foreach (string dir in mails)
                    mm.To.Add(dir);


                //CorreoLog repository = new CorreoLog();

                try
                {
                    sc.Send(mm);
                    //repository.LogMessage(serializedMessage, true);
                    return "Correo enviado";
                    //add to logging db
                }
                catch (Exception ex)
                {
                    //add to logging db
                    //repository.LogMessage(serializedMessage, false);
                    return "Correo no Enviado " + ex.Message;
                    //throw;
                }

            }

        }

        public static string SerializeMessage(EmailMessage message)
        {
            //string result = "text.txt";
            /*MemoryStream oMemoryStream = new MemoryStream();
            StreamWriter tw = new StreamWriter(oMemoryStream, Encoding.Unicode);
            XmlSerializer x = new XmlSerializer(message.GetType());
            x.Serialize(tw, message);
            return tw.ToString();*/
            XmlSerializer oXmlSerializer = null;

            using (MemoryStream oMemoryStream = new MemoryStream())
            {
                using (StreamWriter oStreamWriter = new StreamWriter(oMemoryStream, Encoding.Unicode))
                {
                    oXmlSerializer = new XmlSerializer(message.GetType());
                    oXmlSerializer.Serialize(oStreamWriter, message);
                    int i_Puntero = (int)oMemoryStream.Length;
                    byte[] arr_Bytes = new byte[i_Puntero];
                    oMemoryStream.Seek(0, SeekOrigin.Begin);
                    oMemoryStream.Read(arr_Bytes, 0, i_Puntero);
                    UnicodeEncoding UE = new UnicodeEncoding();
                    return UE.GetString(arr_Bytes).Trim();
                }
            }

        }
    }


    public class EmailMessage
    {
        public string To { get; set; }
        public string From { get; set; }
        public string Subject { get; set; }
        public string Message { get; set; }
    }
      



}
